package com.legrand.core.util;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * 短信下发工具类
 *
 * @author xiah
 */
public class SMSUtils {

    private final static Logger logger = LoggerFactory.getLogger(SMSUtils.class);

    private static final String USERNAME = "xpwb@xpwb";
    private static final String PASSWORD = "Gl9dox6L";

    private static final String SMS_API_URL_TEMPLATE = "http://211.147.239.62:9050/cgi-bin/sendsms?username=${USERNAME}&password=${PASSWORD}&to=${MOBILE_NUM}&text=${SMS_CONTENT}&msgtype=${MSGTYPE}&batchid=${UUID}";


    /**
     * @param mobile
     * @param content
     * @throws UnsupportedEncodingException
     */
    public static String send(String mobile, String content) throws UnsupportedEncodingException {
        OkHttpClient okHttpClient = new OkHttpClient();
        String url = SMS_API_URL_TEMPLATE.replace("${USERNAME}", USERNAME).replace("${PASSWORD}", PASSWORD)
                .replace("${MOBILE_NUM}", mobile).replace("${SMS_CONTENT}", URLEncoder.encode(content, "GB2312"))
                .replace("${MSGTYPE}", content.length() > 58 ? "4" : "1").replace("${UUID}", UUID.randomUUID().toString());
        logger.debug("Send sms by url: {}", url);
        Request request = new Request.Builder().url(url).build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                String code = response.code() + "";
                logger.debug("Send SMS successfully by api, status Code is: {}", code);
                return code;
            } else {
                logger.error("Send SMS failure by api");
            }
        } catch (IOException ex) {
            logger.error("Send SMS failure by network", ex);
        }
        return null;
    }
	public static void main(String[] args) throws UnsupportedEncodingException {
	  send("15012754119","11");
  }
}
